//
//  HMPhotoView.swift
//  HealthMonitoring
//
//  Created by YTYanK on 2018/10/10.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import IDMPhotoBrowser
import TZImagePickerController

class HMPhotoView: NSObject {

    var pv_allowCrop: Bool = false // 允许修剪?
    var pv_Collection: UICollectionView?
    var pv_layout: UICollectionViewFlowLayout?
    var pv_margin: CGFloat = 0.0
 
    // 方块大小
    var pv_itemWH: CGFloat = 0.0
    var pv_collHeight: CGFloat = 130.0
    // -----> 分割线
    var maxCount: Int = 1  ///< 照片最大可选张数，设置为1即为单选模式
    var columnNumber: Int = 0
    var location: CLLocation?
    var imagePickerVc: UIImagePickerController?
    
   // var isOpenStorage: Bool = false  // 是否打开存储对象（用来多选择时用的）
    var pv_isSelectOriginalPhoto: Bool  = false
    var urls = Array<String>()  // url
    // 选中
    private var pv_selectedPhotos = NSMutableArray()
    private var pv_selectedAssets = NSMutableArray()
    private var pc_this: Any?
    private var pv_tzImagePC: TZImagePickerController?
    private var pv_sign: String? // 标记
    open var pickingPhotosBlock: (([UIImage], [Any], Bool)->())?
    open var updatePhotosBlock: (([UIImage], [Any], Bool)->())?

    
    
    
    
   // 获取自身对象
   static let share: HMPhotoView = {
       let instance = HMPhotoView()
       return instance
   }()
    
    
    
    /**
      maxCount  最大选择的数量
     id: id
     */
    func createrPhotoView(this: Any?, maxCount: Int, column:Int, id: String) -> UICollectionView {
        if this != nil {
        self.pc_this = this!
        }
        if self.pv_sign != id {
           self.pv_sign = id
            
            // 清空
           self.pv_selectedPhotos = NSMutableArray()
           self.pv_selectedAssets = NSMutableArray()
           self.pv_isSelectOriginalPhoto = false
            
        }
        self.maxCount = maxCount
        self.columnNumber = column
       
        
        self.pv_Collection = self.configCollectionView()
        return self.pv_Collection!
    }
    
}


extension HMPhotoView: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if pv_selectedPhotos.count >= self.maxCount {
            return pv_selectedPhotos.count
        }
        return pv_selectedPhotos.count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TZTestCell", for: indexPath) as! TZTestCell
        cell.videoImageView.isHidden = true
        
        if indexPath.item ==  pv_selectedPhotos.count {
            cell.imageView.image = UIImage.init(named: "yszs.png")
            cell.deleteBtn.isHidden = true
            cell.gifLable.isHidden = true
        }else {
            cell.imageView.image = pv_selectedPhotos[indexPath.item] as? UIImage
            cell.asset = pv_selectedAssets[indexPath.item]
            cell.deleteBtn.isHidden = false
        }
        //显示动态
        cell.gifLable.isHidden = true
        cell.deleteBtn.tag = indexPath.item
        cell.deleteBtn.addTarget(self, action: #selector(deleteBtnClick), for: .touchUpInside)
        return cell
    }
    
    @objc func deleteBtnClick(sender: UIButton) {
        //删除事件
        if self.collectionView(self.pv_Collection!, numberOfItemsInSection: 0) <= self.pv_selectedPhotos.count {
            self.pv_selectedPhotos.removeObject(at: sender.tag)
            self.pv_selectedAssets.removeObject(at: sender.tag)
            self.pv_Collection?.reloadData()
            return
        }
        
        
        self.pv_selectedPhotos.removeObject(at: sender.tag)
        self.pv_selectedAssets.removeObject(at: sender.tag)
        
        self.pv_Collection?.performBatchUpdates({
            let index: IndexPath = NSIndexPath.init(item: sender.tag, section: 0) as IndexPath
            self.pv_Collection?.deleteItems(at: [index])
            
        }, completion: { (isfinished) in
            self.pv_Collection?.reloadData()
        })
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.item == pv_selectedAssets.count {
             print("相册选择/拍照")
            
            let tabkePhotoTitle = "拍照"
            let alertVc = UIAlertController.init(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
            let takePhotoAction = UIAlertAction.init(title: tabkePhotoTitle, style: UIAlertActionStyle.default) { (action) in
                // 事件
                print("拍照")
                self.takePhoto(self)
            }
            alertVc.addAction(takePhotoAction)
            
            //去相册选择
            let imagePickerAction = UIAlertAction.init(title: "去相册选择", style: .default) { (imgAction) in
                // 事件
                print("去相册选择")
                
                let imagePicker = self.pushImagePickerController(self.pc_this!, max: self.maxCount, column: self.columnNumber, selectedAssets: self.pv_selectedAssets)
               
                /// 你可以通过block或者代理，来得到用户选择的照片.
                imagePicker.didFinishPickingPhotosHandle = {
                    (photos: [UIImage]!, assets: [Any]!, isSelectOriginalPhoto: Bool) -> () in
                    //
                    
                    self.pv_selectedAssets = NSMutableArray.init(array: assets)
                    self.pv_selectedPhotos = NSMutableArray.init(array: photos)
                    self.pv_isSelectOriginalPhoto = isSelectOriginalPhoto
                    self.pv_Collection?.reloadData() // 更新组件
                    if self.pickingPhotosBlock != nil {
                        self.pickingPhotosBlock!(photos,assets,isSelectOriginalPhoto)
                    }
                }
                
            }
            alertVc.addAction(imagePickerAction)
            
            let canceAction = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
            
            alertVc.addAction(canceAction)
            // --- ---- 位置
            //            let popover : UIPopoverPresentationController  = alertVc.popoverPresentationController!
            //            let cell : UICollectionViewCell = collectionView.cellForItem(at: indexPath)!
            //            if popover != nil {
            //                popover.sourceView = cell
            //                popover.sourceRect = cell.bounds
            //                popover.permittedArrowDirections = UIPopoverArrowDirection.any
            //            }
            
            let vc =  self.pc_this as! UIViewController
            vc.present(alertVc, animated: true, completion: nil)
   
        }else {
             print("预览部分照片")
//            let asset: PHAsset = self.pv_selectedAssets[indexPath.item] as! PHAsset
            let previewPickerVc =  self.showImagePickerController(self.pc_this, photos: (self.pv_selectedPhotos as! [UIImage]), assets: (self.pv_selectedAssets as! [Any]), index: indexPath.item, max: self.maxCount)
            previewPickerVc.didFinishPickingPhotosHandle = {
                (photos, assets, isSelectOriginalPhoto) -> () in
                
                self.pv_selectedAssets = NSMutableArray.init(array: assets!)
                self.pv_selectedPhotos = NSMutableArray.init(array: photos!)
                self.pv_isSelectOriginalPhoto = isSelectOriginalPhoto
                self.pv_Collection?.reloadData() // 更新组件
                self.pv_Collection?.contentSize = CGSize.init(width: 0, height: ((CGFloat(self.pv_selectedPhotos.count) + 2.0) / 3.0) * (self.pv_margin + self.pv_itemWH))
            }
        }
    }
    
    
    /// 创建一个collectionView
    func configCollectionView()-> UICollectionView {
        pv_layout = UICollectionViewFlowLayout()
        let coll = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: pv_layout!)
        coll.backgroundColor = UIColor.red
        coll.alwaysBounceVertical = true
        coll.isScrollEnabled = false //禁止滑动
        
        coll.contentInset = UIEdgeInsetsMake(4, 4, 4, 4)
        coll.register(TZTestCell.classForCoder(), forCellWithReuseIdentifier: "TZTestCell")
        coll.dataSource = self
        coll.delegate = self
        
        pv_margin = 4.0
        pv_itemWH = (configure.shareConfigure.screenWidth - 16.0 - 2.0 * pv_margin - 4.0) / 3 - pv_margin
        pv_layout?.itemSize = CGSize(width: pv_itemWH, height: pv_itemWH)
        pv_layout?.minimumInteritemSpacing = pv_margin
        pv_layout?.minimumLineSpacing = pv_margin
        coll.setCollectionViewLayout(pv_layout!, animated: true)
        let collectionViewY: CGFloat = 0.0
        coll.frame = CGRect(x: 0, y: collectionViewY, width: configure.shareConfigure.screenWidth, height: pv_collHeight)
        
        return coll
    }

}


/// pragma mark - TZImagePickerControllerDelegate
extension HMPhotoView: TZImagePickerControllerDelegate {

    /// 一串字符串路径？
    class func showPhotoBrowser(urls: String, index: Int) {
        let array = urls.components(separatedBy: ";")
        showPhotoBrowser(urls: array, index: index)
    }
    
    class func showPhotoBrowser(urls: [String], index: Int) {
        var photos:[IDMPhoto] = []
        
        for url in urls {
            if url == "" {
                continue
            }
            //            let uuu = URL(string: url)
            if let photo = IDMPhoto(url: URL(string: url)) {
                photos.append(photo)
            }
        }
        if let browser = IDMPhotoBrowser(photos: photos) {
            browser.dismissOnTouch = true
            browser.displayDoneButton = false
            browser.displayActionButton = false
            browser.usePopAnimation = true
            let idx = UInt(index)
            browser.setInitialPageIndex(idx)
            if let vc = UIApplication.shared.keyWindow?.rootViewController {
                vc.present(browser, animated: true) {
                    //
                }
            }
        }
    }
    
    
    
    public func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingVideo coverImage: UIImage!, sourceAssets asset: Any!) {
        print("回调---->>视频  didFinishPickingVideo")
    }
    
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingGifImage animatedImage: UIImage!, sourceAssets asset: Any!) {
        print("回调---->>动态图片 didFinishPickingGifImage")
    }
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool) {
        
        
        if photos.count > 0 {
            var datas: [Data]?
            var imgsStr: [String]?
            for i in 0..<photos.count {
                let dataImg: Data = UIImage.compressImageSize(image: photos[i]) as Data
                let originalImagSize = dataImg.count/1024 as Int
                print("id: \(i) 原始大小: \(originalImagSize)")
                  imgsStr?.append("图片\(i)")
                  datas?.append(dataImg)
            }
        }else {
            // 返回 0
        }
        
        
        picker.dismiss(animated: true) {
            
        }
        
    }
    
}


extension HMPhotoView {
   ///  压缩图片 及  UIImage 转 Data
    class func requesHeadImages(photos: [UIImage], assets:[Any]?) ->(datas: [Data], imgAssets:[Any]){
        let new_date = Date()
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let dateStr = formatter.string(from: new_date)
        // 当前 时间字符
        
        let datas = NSMutableArray()
        let imgAssets = NSMutableArray()
        var i = 0
        for photo in photos {
            print("192 HMPhotoView :打印：------>",photo)
            let zipImageData: Data = UIImageJPEGRepresentation(photos[i], 0.2)!
            var str = ""
            if assets != nil {
              str = "\(dateStr)-\(assets![i])"
            }else {
              str = "\(dateStr)-\(i)"
            }
            imgAssets.add(str)
            datas.add(zipImageData)
            i += 1
        }
        return (datas as! [Data], imgAssets as! [Any])
    }
    /// 拍照
    func takePhoto(_ target: Any?) {
        let authStatus :AVAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
        
        let _tar =  target as! UIViewController //转
        
        if authStatus == AVAuthorizationStatus.restricted || authStatus == AVAuthorizationStatus.denied {
            // 无相机权限 做一个友好的提示
            let alert = UIAlertController(title: "无法使用相机", message: "请在iPhone的 \"设置-隐私-相机\" 中允许访问相机", preferredStyle: UIAlertControllerStyle.alert)
            let action = UIAlertAction(title: "取消", style: UIAlertActionStyle.default, handler: { (alertAction) in
                
            })
            alert.addAction(action)
            _tar.present(alert, animated: true, completion: nil)
            
        }else if authStatus == AVAuthorizationStatus.notDetermined {
            // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
            AVCaptureDevice.requestAccess(for: AVMediaType.video) { (granted) in
                if granted {
                    //                    dispatch_async(dispatch_get_main_queue(), ^{
                    //                        [self takePhoto];
                    //                        });
                }
            }
            
        }else if PHPhotoLibrary.authorizationStatus().rawValue == 2 {
            let alert = UIAlertController(title: "无法访问相册", message: "请在iPhone的\"设置-隐私-相册\"中允许访问相册", preferredStyle: UIAlertControllerStyle.alert)
            let action = UIAlertAction(title: "取消", style: UIAlertActionStyle.default, handler: { (alertAction) in
                ///
            })
            alert.addAction(action)
            _tar.present(alert, animated: true, completion: nil)
            
        }else if PHPhotoLibrary.authorizationStatus().rawValue == 0 { // 未请求过相册权限
            TZImageManager.default()?.requestAuthorization(completion: {
                self.takePhoto(target)
            })
        }else {
            self.pushImagePickerController(target: target)
        }
    }
    
    /// 调用相机
    func pushImagePickerController(target: Any?) {
        //定位
        TZLocationManager().startLocation(successBlock: { (locations) in
            print("locations?.first---->\(locations?.first)")
            self.location = locations?.first
            
        }) { (error) in
            print("error---->\(String(describing: error))")
            self.location = nil
        }
        
        let sourceType = UIImagePickerControllerSourceType.camera
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
            //            self.image
        }
        
    }
    /// 原生选择器？
    func getImagePickerVc(_ target: Any?) -> UIImagePickerController {
        let tar: UIViewController = target as! UIViewController
        if self.imagePickerVc == nil {
            imagePickerVc = UIImagePickerController()
            imagePickerVc?.delegate = HMPhoto.shareInstance
            imagePickerVc?.navigationBar.barTintColor = tar.navigationController?.navigationBar.tintColor
            let tzBarItem: UIBarButtonItem
            let BarItem : UIBarButtonItem
            //            if #available(iOS 9,  *) {
            //                tzBarItem = UIBarButtonItem.appearance(whenContainedInInstancesOf: [TZImagePickerController.classForCoder() as! UIAppearanceContainer.Type])
            //
            //                BarItem = UIBarButtonItem.appearance(whenContainedInInstancesOf: [UIImagePickerController.classForCoder()])
            //            }else {
            //                tzBarItem = UIBarButtonItem.appearance(for: <#T##UITraitCollection#>, whenContainedInInstancesOf: <#T##[UIAppearanceContainer.Type]#>)
            //            }
        }
        return imagePickerVc!
        
    }
    
    
    
   /// 每次调用会重新创建一个 imagePickerVc 对象
    func pushImagePickerController(_ target:Any?, max: Int, column: Int, selectedAssets: NSMutableArray) -> TZImagePickerController{
        // 最大照片数)
//        self.maxCount = max
        // 行向布局列的个数
//        self.columnNumber = column
        
        var newMax = max
        if max <= 0 {
            newMax = 1
//            return
        }
        
        let imagePickerVc = TZImagePickerController.init(maxImagesCount: newMax, columnNumber: column, delegate: self, pushPhotoPickerVc: true)
        
        /// pragma mark - 五个、个性化设置，这些参数都可以不传，此时会走默认设置
        imagePickerVc?.isSelectOriginalPhoto = self.pv_isSelectOriginalPhoto //原图？
        if max > 1 {
            // 选择的路径
            imagePickerVc?.selectedAssets =  selectedAssets //self.pv_selectedAssets
        }
        // 在内部显示拍照按钮
        imagePickerVc?.allowTakePicture = true
        // 在内部显示拍视频按
        imagePickerVc?.allowTakeVideo = false
        // 视频最大拍摄时间
        imagePickerVc?.videoMaximumDuration = 10
        imagePickerVc?.uiImagePickerControllerSettingBlock = {
             (imagePickerController : UIImagePickerController!) -> ()in
            imagePickerController.videoQuality = UIImagePickerControllerQualityType.typeHigh
        }
        
        
        // 2.设置 imagePickerVc 外观
        imagePickerVc?.iconThemeColor = configure.shareConfigure.HMColor1
        imagePickerVc?.showPhotoCannotSelectLayer = true
        imagePickerVc?.cannotSelectLayerColor = UIColor.white.withAlphaComponent(0.8)
//        imagePickerVc?.photoPickerPageUIConfigBlock = ({
//            (collectionView:UICollectionView, bottomToolBar:UIView, previewButton:UIButton, originalPhotoButton:UIButton, originalPhotoLabel: UILabel, doneButton: UIButton,  numberImageView: UIImageView,  numberLabel: UILabel, divideLine: UIView) ->() in
//
//
//            } as! (UICollectionView?, UIView?, UIButton?, UIButton?, UILabel?, UIButton?, UIImageView?, UILabel?, UIView?) -> Void)
        
        // 3. 设置是否可以选择视频/图片/原图
        imagePickerVc?.allowPickingVideo = false
        imagePickerVc?.allowPickingImage = true
        imagePickerVc?.allowPickingGif = false
        imagePickerVc?.allowPickingOriginalPhoto = true
        imagePickerVc?.allowPickingMultipleVideo = false
        // 4. 照片排列按修改时间升序
        imagePickerVc?.sortAscendingByModificationDate = false
        // 5. 单选模式,maxImagesCount为1时才生效
        imagePickerVc?.showSelectBtn = false
        imagePickerVc?.allowCrop = self.pv_allowCrop // 允许修剪?
        imagePickerVc?.needCircleCrop = false
        
        // 设置竖屏下的裁剪尺寸
        let left: NSInteger = 30
        let widthHeight: NSInteger = Int(configure.shareConfigure.screenWidth) - 2 * left
        let top: NSInteger = (Int(configure.shareConfigure.screenHeight) - widthHeight)/2
        imagePickerVc?.cropRect = CGRect.init(x: left, y: top, width: widthHeight, height: widthHeight)
        
        // 设置是否显示图片序号
        imagePickerVc?.showSelectedIndex = true
        
        
//        self.pv_tzImagePC = imagePickerVc!
//        imagePickerVc?.didFinishPickingPhotosHandle = {
//             (photos: [UIImage]!, assets: [Any]!, isSelectOriginalPhoto: Bool) -> () in
////            print("========>>>", photos, assets)
//        }
        // 弹出显示
        if target != nil {
        let vc = target as! UIViewController
           vc.present(imagePickerVc!, animated: true, completion: nil)
        }
        return imagePickerVc!
    }
    
    /// 预览 = 返回一个预览用的 TZImagePickerController 对象
    func showImagePickerController(_ target: Any?, photos: [UIImage]!, assets: [Any]!, index: NSInteger, max: Int) -> TZImagePickerController {
        let mutableAssets = NSMutableArray.init(array: assets)
        let mutablePhotos = NSMutableArray.init(array: photos)
        
        let imagePickerVc: TZImagePickerController = TZImagePickerController.init(selectedAssets: mutableAssets, selectedPhotos: mutablePhotos, index: index)
        imagePickerVc.maxImagesCount = max
        imagePickerVc.allowPickingGif = false
        imagePickerVc.allowPickingOriginalPhoto = true
        imagePickerVc.allowPickingMultipleVideo = false
        imagePickerVc.showSelectedIndex = true
        imagePickerVc.isSelectOriginalPhoto = self.pv_isSelectOriginalPhoto
        let  vc = target as! UIViewController
        vc.present(imagePickerVc, animated: true, completion: nil)
        return imagePickerVc
    }
    
 
}

extension HMPhotoView {
    
    
     //MARK: - 上传图片到后台
    /**
      上传图片到后台 ()
     photos - 任意图片数组
     */
    class func requestImages(photos:[UIImage]!, block:@escaping ()->()) {
        
        // 添加前先清空
         HMPhotoView.share.urls.removeAll()
        var i = 0
        for image in photos {
            
            // 简单压缩
            let zipImageData: Data = UIImageJPEGRepresentation(image, 0.2)!
            
            // 时间
            let _date = Date()
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            let dateString = formatter.string(from: _date)
            
            // 上传
            NetRequestTool.shareInstance.met = .post
            NetRequestTool.upload(url: "/user/image/upload", data:[zipImageData] ,imgName: [dateString] ,parameters: [:], success: { (json) in
                HMPhotoView.share.urls.append(json["url"].stringValue)
                if HMPhotoView.share.urls.count ==  (i + 1) {
                    block()
                }
            }) { (err, msg) in
                print("上传失败", err, msg)
                HMPhotoView.share.urls.append("no url")
                if HMPhotoView.share.urls.count ==  (i + 1) {
                    block()
                }
            }
            i += 1
        }
    }
}
